package com.netease.nie.base.handlers;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.netease.nie.base.exceptions.BusinessException;
import com.netease.nie.base.exceptions.UnexpectedException;
import com.netease.nie.base.protocol.SystemResponseCode;
import com.netease.nie.base.utils.ProtocolUtils;

/**
 * 
 * @author KingsHunter
 * @createDate May 28th,2016
 * 
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	private Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = BusinessException.class)
	@ResponseBody
	public String jsonErrorHandler(HttpServletRequest req, BusinessException e) throws Exception {
		logger.info("业务异常：" + e.getMsg());
		return ProtocolUtils.populateResponseJson(e.getErrorCode(), e.getMsg());
	}

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public String jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		logger.error("内部异常", e);
		return ProtocolUtils.populateResponseJson(SystemResponseCode.INTERNAL_ERROR.getCode(), SystemResponseCode.INTERNAL_ERROR.getMsg());
	}

	@ExceptionHandler(UnexpectedException.class)
	@ResponseBody
	public String jsonErrorHandler(HttpServletRequest req, UnexpectedException e) throws Exception {
		logger.error("未知异常", e);
		return ProtocolUtils.populateResponseJson(SystemResponseCode.UNKOWN_ERROR.getCode(), StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : SystemResponseCode.UNKOWN_ERROR.getMsg());
	}
}
